package c_000;

public class T03_Sleep_Yield_Join {
    public static void main(String[] args) {
//        testSleep();
//        testYield();
        testJoin();
    }

    //当前线程休眠,把资源让给其他线程,sleep完回到就绪状态
    static void testSleep(){
        new Thread(() ->{
           for(int i = 0; i < 100; i++){
               System.out.println("A" + i);
               try {
                   Thread.sleep(500);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
           }
        }).start();
    }

    //返回就绪状态,让出一下cpu资源,进入等待队列
    static void testYield(){
        new Thread(() ->{
            for(int i = 0; i < 100; i++){
                System.out.println("A" + i);
                if(i % 10 == 0) Thread.yield();
            }
        }).start();

        new Thread(() -> {
            for(int i = 0; i < 100; i++){
                System.out.println("B" + i);
                if(i % 10 == 0) Thread.yield();
            }
        }).start();
    }

    static void testJoin(){
        Thread t1 = new Thread(() ->{
            for(int i = 0; i < 100; i++){
                System.out.println("A" + i);
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        Thread t2 = new Thread(() ->{
            try {
                //t1.join(),表示等t1的任务执行完成再执行t2的任务,可用于线程之间排序
//                t1.join();
                for(int i = 0; i < 100; i++){
                    System.out.println("B" + i);
                    Thread.sleep(500);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        t1.start();
        t2.start();
    }


}
